package com.pyb.common.mybatis.handlers;

import com.pyb.common.utils.DateTimeUtil;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeException;
import org.joda.time.DateTime;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * DateTimeTypeHandler
 *
 * @author chuchen.zhang
 * @date 17-2-27 下午3:24
 */
public class DateTimeTypeHandler extends BaseTypeHandler<DateTime>{

	@Override
	public void setNonNullParameter(PreparedStatement preparedStatement, int i, DateTime dateTime, JdbcType jdbcType) throws SQLException {
		preparedStatement.setString(i, DateTimeUtil.fmtYyyyMMddHHmmss(dateTime));
	}

	@Override
	public DateTime getResult(ResultSet rs, String columnName) throws SQLException {

		try {
			String dateTimeStr = rs.getString(columnName);

			if (rs.wasNull()) {
				return null;
			}
			return DateTimeUtil.parseYyyyMMddHHmmssSSS(dateTimeStr);

		} catch (Exception e) {
			throw new TypeException("Exception while invoking valueOf method", e);
		}
	}

	public DateTime getResult(ResultSet rs, int columnIndex) throws SQLException {

		try {

			String dateTimeStr = rs.getString(columnIndex);

			if (rs.wasNull()) {
				return null;
			}
			return DateTimeUtil.parseYyyyMMddHHmmssSSS(dateTimeStr);

		} catch (Exception e) {
			throw new TypeException("Exception while invoking valueOf method", e);
		}
	}

	public DateTime getResult(CallableStatement cs, int columnIndex) throws SQLException {

		try {

			String dateTimeStr = cs.getString(columnIndex);

			if (cs.wasNull()) {
				return null;
			}
			return DateTimeUtil.parseYyyyMMddHHmmssSSS(dateTimeStr);

		} catch (Exception e) {
			throw new TypeException("Exception while invoking valueOf method", e);
		}
	}

	@Override
	public DateTime getNullableResult(ResultSet resultSet, String s) throws SQLException {
		return null;
	}

	@Override
	public DateTime getNullableResult(ResultSet resultSet, int i) throws SQLException {
		return null;
	}

	@Override
	public DateTime getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
		return null;
	}
}
